import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Descriptions, Button, message, Tag, Divider } from 'antd';
import { history, useParams } from 'umi';
import { ArrowLeftOutlined, EditOutlined } from '@ant-design/icons';
import { getRole, RoleData } from '@/services/role';

const RoleDetailPage: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [role, setRole] = useState<RoleData | null>(null);
  const { id } = useParams<{ id: string }>();

  useEffect(() => {
    const fetchRole = async () => {
      try {
        const response = await getRole(Number(id));
        if (response.success && response.data) {
          setRole(response.data);
        } else {
          message.error(response.message || '获取角色信息失败');
        }
      } catch (error) {
        console.error('获取角色信息出错:', error);
        message.error('获取角色信息失败');
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchRole();
    } else {
      setLoading(false);
    }
  }, [id]);

  const handleEdit = () => {
    if (id) {
      history.push(`/role/edit/${id}`);
    }
  };

  if (loading) {
    return <div>加载中...</div>;
  }

  if (!role) {
    return <div>角色不存在</div>;
  }

  return (
    <PageContainer
      header={{
        title: '角色详情',
        breadcrumb: {
          items: [
            { title: '系统管理' },
            { title: '角色管理', path: '/role/list' },
            { title: '角色详情' },
          ],
        },
        extra: [
          <Button
            key="edit"
            type="primary"
            icon={<EditOutlined />}
            onClick={handleEdit}
          >
            编辑
          </Button>,
        ],
      }}
    >
      <Card>
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />} 
          onClick={() => history.back()}
          style={{ marginBottom: 16 }}
        >
          返回
        </Button>
        
        <Descriptions title="基本信息" bordered column={2}>
          <Descriptions.Item label="角色名称">{role.name}</Descriptions.Item>
          <Descriptions.Item label="状态">
            {role.status ? (
              <Tag color="success">启用</Tag>
            ) : (
              <Tag color="error">禁用</Tag>
            )}
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {role.createdAt ? new Date(role.createdAt).toLocaleString() : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="描述" span={2}>
            {role.description || '-'}
          </Descriptions.Item>
        </Descriptions>

        {/* 权限列表部分可以在后续实现权限管理功能时添加 */}
      </Card>
    </PageContainer>
  );
};

export default RoleDetailPage;
